#include "widget.h"
#include "ui_widget.h"
#include <QMessageBox>
#include <QTcpSocket>
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->setWindowTitle("服务器");
    tcpServer = new QTcpServer(this);
    connect(tcpServer, &QTcpServer::newConnection, this, &Widget::processConnection);
    bool ret = tcpServer->listen(QHostAddress::Any, 9090);

    if (!ret)
    {

    }
}

Widget::~Widget()
{
    delete ui;
}

void Widget::processConnection()
{
    QTcpSocket* clientSocket = tcpServer->nextPendingConnection();
    QString log = "[" + clientSocket->peerAddress().toString() + ":" + QString::number(clientSocket->peerPort()) +
            "] 客户端上线";
    ui->listWidget->addItem(log);
    connect(clientSocket, &QTcpSocket::readyRead, this, [=](){
        QString request = clientSocket->readAll();
        const QString& response = process(request);
        clientSocket->write(response.toUtf8());
        QString log = "[" + clientSocket->peerAddress().toString() + ":" + QString::number(clientSocket->peerPort()) +
                "]" + "req:" +request + ", resp:" + response;
        ui->listWidget->addItem(log);
    });

    connect(clientSocket, &QTcpSocket::disconnected, this, [=](){
        QString log = "[" + clientSocket->peerAddress().toString() + ":" + QString::number(clientSocket->peerPort()) + "]客户端下线";
        ui->listWidget->addItem(log);
        clientSocket->deleteLater();
    });

}
//回显服务器
QString Widget::process(const QString request)
{
    return request;
}

